package storage

import (
	"context"
	"encoding/json"
	"time"

	"gitcode.com/eteam/sae.git/types"
	"github.com/redis/go-redis/v9"
)

type _EventDao struct {
	client *redis.Client
}

const (
	_TASK_EVENT_CHANNEL_PREFIX = "taskev:"
)

func (dao *_EventDao) Publish(ctx context.Context, taskId string, obj types.ObjectKindAware) error {
	jsonData, err := json.Marshal(obj)
	if err != nil {
		return err
	}
	newCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	channel := _TASK_EVENT_CHANNEL_PREFIX + taskId
	return dao.client.Publish(newCtx, channel, jsonData).Err()
}

func (dao *_EventDao) Subscribe(ctx context.Context, taskId string) *redis.PubSub {
	channel := _TASK_EVENT_CHANNEL_PREFIX + taskId
	return dao.client.Subscribe(ctx, channel)
}
